<template>
  <view class="product-card" :class="{ 'order-mode': orderMode }">
    <!-- 顶部信息区（可选） -->
    <view v-if="showTopInfo" class="top-info">
      <view class="left-text">{{ info.businessType || '研学接待业务' }}</view>
      <view class="right-status">{{ info.refundPolicy || '开营前7天无损退' }}</view>
    </view>

    <!-- 主要内容区 -->
    <view class="content-area">
      <!-- 产品图片 -->
      <view class="image-container" @click="goToProductDetail">
        <image :src="info.mainImage || info.mainInfo?.productSpu?.mainImage || info.ImageUrl" mode="aspectFill"
          class="product-image" @error="onImageError"></image>
      </view>

      <!-- 产品信息 -->
      <view class="info-container">
        <!-- 产品标题 -->
        <view class="product-title ellipsis-multi">{{ getProductTitle }}<text v-if="info.mainInfo?.productSpu?.name"> |
            {{ info.mainInfo.productSpu.name }}</text></view>
        <!-- 产品基本信息 -->
        <view class="basic-info">


          <view class="info-item">
            <FontIcon name="icon-xiaohai" wrapperWidth="0rpx" wrapperHeight="0rpx" :size="28"
              style="margin-left: 12rpx;margin-bottom: 6rpx;margin-right: 26rpx;" class="info-icon"></FontIcon>
            <text class="info-text">{{ getAgeRange }}</text>
          </view>

          <view class="info-item">
            <FontIcon name="icon-time1" :size="28" style="margin-bottom: 6rpx;" wrapperWidth="0rpx" wrapperHeight="0rpx" class="info-icon">
            </FontIcon>
            <text class="info-text">{{ getDuration }}</text>
          </view>

          <view class="info-item">
            <FontIcon name="icon-address1" :size="28" style="margin-bottom: 6rpx;" wrapperWidth="0rpx" wrapperHeight="0rpx" class="info-icon">
            </FontIcon>
            <text class="info-text ellipsis-single" :style="{ maxWidth: '150rpx' }">{{ getAddress }}</text>
          </view>
        </view>

        <!-- 产品标签和价格 -->
        <view class="tag-price-container">
          <view class="tags-container">
            <view v-for="(tag, index) in getTags" :key="index" class="tag-item" :style="getTagStyle(tag)">
              {{ tag.text }}
            </view>
            <!-- 订单模式下显示接送信息 -->
            <view v-if="orderMode && info.pickupInfo" class="tag-item pickup-tag">
              {{ info.pickupInfo }}
            </view>
          </view>

          <view class="price-container">
            <text v-if="!orderMode" class="price-symbol">渠道:</text>
            <view class="price-value">
              <text class="currency">¥</text>
              <text class="price-int">{{ priceParts.intPart }}</text>
              <text class="price-dec">.{{ priceParts.decPart }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 日期选择区（可选） -->
    <view v-if="showDateSelect && info.availableDates && info.availableDates.length > 0" class="date-selector">
      <u-icon name="calendar" size="24" color="#78A329"></u-icon>
      <view class="date-box" v-for="(date, index) in getDisplayDates" :key="index">
        {{ date }}
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'ProductCard',
  props: {
    // 产品信息对象
    info: {
      type: Object,
      default: () => ({})
    },
    // 是否显示顶部信息
    showTopInfo: {
      type: Boolean,
      default: false
    },
    // 是否显示日期选择
    showDateSelect: {
      type: Boolean,
      default: false
    },
    // 是否为订单模式
    orderMode: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    // 获取产品标题
    getProductTitle() {
      const { info } = this
      console.log('info1', info)
      return info.mainInfo?.productSku?.title || info.mainInfo?.productSpu?.title || info.Title || '未命名产品'
    },

    // 获取年龄范围
    getAgeRange() {
      const { info } = this
      if (info.mainInfo?.productSku?.minYearOld && info.mainInfo?.productSku?.maxYearOld) {
        return `${info.mainInfo.productSku.minYearOld}~${info.mainInfo.productSku.maxYearOld}岁`
      }
      return info.NianLing || '不限年龄'
    },

    // 获取活动时长
    getDuration() {
      const { info } = this
      if (info.mergedItineraries && info.mergedItineraries.length > 0) {
        return `${info.mergedItineraries.length}日`
      }
      return info.ShiChang || '未知'
    },

    // 获取活动地址
    getAddress() {
      const { info } = this;

      // 获取地址的过程
      if (info.mergedItineraries && info.mergedItineraries.length > 0 &&
        info.mergedItineraries[0].details && info.mergedItineraries[0].details.length > 0) {

        const address = info.mergedItineraries[0].details[0].items[0].address;

        if (address) {
          // 查找“省”和“市”的位置
          const provinceIndex = address.indexOf('省');
          const cityIndex = address.indexOf('市');

          // 如果找到“省”和“市”，并且“市”位于“省”后面，提取省市部分
          if (provinceIndex !== -1 && cityIndex !== -1 && cityIndex > provinceIndex) {
            // 提取省市部分，返回“河南郑州”
            return address.slice(0, cityIndex).replace('省', '');
          }

          // 如果找不到“省”，但有“市”，返回省市部分
          if (cityIndex !== -1) {
            // 处理“市”前的部分，返回“河南郑州”
            return address.slice(0, cityIndex).replace('省', '');
          }

          return address; // 如果没有“市”，则返回整个地址
        }
      }

      // 如果没有找到mergedItineraries地址信息，则查找备用地址
      const address_sf = info.Address_sf || '';
      const address_ds = info.Address_ds || '';

      if (address_sf || address_ds) {
        const fullAddress = (address_sf + address_ds).trim();

        // 查找“市”的位置并处理
        const cityIndex = fullAddress.indexOf('市');
        if (cityIndex !== -1) {
          const provinceIndex = fullAddress.indexOf('省');
          if (provinceIndex !== -1) {
            // 提取省市部分，返回“河南郑州”
            return fullAddress.slice(provinceIndex + 1, cityIndex).replace('省', '');
          }
          // 如果没有省，返回市名
          return fullAddress.slice(0, cityIndex + 1);
        }
        return fullAddress; // 如果没有“市”，则返回完整地址
      }

      // 如果所有地址为空或undefined，返回“未提供地址”
      return '未提供地址';
    }

    ,

    // 获取产品标签
    getTags() {
      const { info } = this
      const tags = []
      console.log('info2', info)

      const channelTag = info.ChannelName || info.LBTag1
      if (channelTag) {
        tags.push({ text: channelTag })
      }

      const productTag = info.TagName || (info.tag && info.tag.length > 0 ? info.tag[0].TagName : '')
      if (productTag) {
        tags.push({ text: productTag })
      }

      // 根据 productType 判断商家类型来选择地址来源
      // productType === 1,3目的地接待或者泛营地接待，取 getAddress
      // productType === 2, 4：组团与综合研学与研学活动，取 saleAreaProcessed
      // productType === 5:研学活动，取 saleAreaProcessed
      const productType = Number(info.mainInfo?.productSpu?.productType) || 0
      
      if (productType === 1||productType===3) {
        // 目的地接待或者泛营地接待：直接从 mergedItineraries 获取地址，只显示市名并去掉"市"字
        const address = info.mergedItineraries && info.mergedItineraries[0] && 
          info.mergedItineraries[0].details && info.mergedItineraries[0].details[0] && 
          info.mergedItineraries[0].details[0].items && info.mergedItineraries[0].details[0].items[0] ? 
          info.mergedItineraries[0].details[0].items[0].address : null
        if (address && address !== '未提供地址') {
          console.log('address', address)
          // 提取市名：例如 "福建省漳州市" -> "漳州"
          let cityName = address
          // 如果包含"市"，提取第一个"市"字前面的部分
          if (cityName.includes('市')) {
            const cityIndex = cityName.indexOf('市')
            if (cityIndex > 0) {
              // 提取"市"字前面的部分
              cityName = cityName.substring(0, cityIndex)
              // 去掉省、自治区等前缀，只保留市名
              // 例如 "福建省漳州" -> "漳州"
              const provinceIndex = cityName.lastIndexOf('省')
              const regionIndex = cityName.lastIndexOf('自治区')
              if (provinceIndex >= 0) {
                cityName = cityName.substring(provinceIndex + 1)
              } else if (regionIndex >= 0) {
                cityName = cityName.substring(regionIndex + 2)
              }
            }
          }
          const suffix = this.getProductTypeSuffix(productType)
          tags.push({ text: suffix ? `${cityName}${suffix}` : cityName })
        } else {
          tags.push({ text: '待设置', isPlaceholder: true })
        }
      } else if ([2, 4, 5].includes(productType)) {
        // 组团与综合研学与研学活动（productType 2,4,5）
        const saleAreaRaw = info.mainInfo?.saleArea || info.saleArea || info.SaleArea
        let areaProcessed = ''
        console.log('saleAreaRaw', saleAreaRaw)
        // 组团与综合研学与研学活动（productType = 2, 4，5）：显示区级，例如 "福建省漳州市龙文区" -> "龙文接送"
        areaProcessed = this.extractDistrictLevel(saleAreaRaw)
        console.log('areaProcessed', areaProcessed)
        if (areaProcessed) {
          const suffix = this.getProductTypeSuffix(productType)
          tags.push({ text: suffix ? `${areaProcessed}${suffix}` : areaProcessed })
        } else {
          // 如果 saleArea 为空，直接显示"待设置"
          tags.push({ text: '待设置', isPlaceholder: true })
        }
      } else {
        // 如果 productType 无法识别，使用默认逻辑（二类商家逻辑）
        const saleAreaRaw = info.mainInfo?.saleArea || info.saleArea || info.SaleArea
        const saleAreaProcessed = this.extractSaleAreaCity(saleAreaRaw)
        if (saleAreaProcessed) {
          const suffix = this.getProductTypeSuffix(productType)
          tags.push({ text: suffix ? `${saleAreaProcessed}${suffix}` : saleAreaProcessed })
        } else {
          // 如果为待设置，多判断一层，检查是否存在 mergedItineraries 地址
          const address = info.mergedItineraries && info.mergedItineraries[0] && 
            info.mergedItineraries[0].details && info.mergedItineraries[0].details[0] && 
            info.mergedItineraries[0].details[0].items && info.mergedItineraries[0].details[0].items[0] ? 
            info.mergedItineraries[0].details[0].items[0].address : null
          if (address && address !== '未提供地址') {
            // 提取市名：例如 "福建省漳州市" -> "漳州"
            let cityName = address
            if (cityName.includes('市')) {
              const cityIndex = cityName.indexOf('市')
              if (cityIndex > 0) {
                cityName = cityName.substring(0, cityIndex)
                const provinceIndex = cityName.lastIndexOf('省')
                const regionIndex = cityName.lastIndexOf('自治区')
                if (provinceIndex >= 0) {
                  cityName = cityName.substring(provinceIndex + 1)
                } else if (regionIndex >= 0) {
                  cityName = cityName.substring(regionIndex + 2)
                }
              }
            }
            const suffix = this.getProductTypeSuffix(productType)
            tags.push({ text: suffix ? `${cityName}${suffix}` : cityName })
          } else {
            tags.push({ text: '待设置', isPlaceholder: true })
          }
        }
      }

      return tags
    },

    // 获取产品价格（原始值，可能为字符串/数字）
    getPrice() {
      console.log('this.info',this.info)
      const { info } = this
      return info.mainInfo?.price || info.Amount || 0
    },

    // 价格拆分（保留两位小数，拆为整数与小数部分）
    priceParts() {
      const num = Number(this.getPrice) || 0
      const fixed = num.toFixed(2)
      const [intPart, decPart] = fixed.split('.')
      return { intPart, decPart: decPart || '00' }
    },

    // 获取显示的日期（限制数量）
    getDisplayDates() {
      const { info } = this
      if (!info.availableDates || info.availableDates.length === 0) {
        return []
      }
      // 最多显示3个日期
      return info.availableDates.slice(0, 3)
    },

    // 获取商家类型
    businessType() {
      try {
        const companyInfo = uni.getStorageSync('companyInfo') || {}
        return companyInfo.businessType || 1
      } catch (e) {
        return 1
      }
    },

    // 标签样式（根据数据来源 p1/p2/p3 动态设置）
    baseTagStyle() {
      const { info } = this
      const productType = Number(info.mainInfo?.productSpu?.productType) || 0
      
      // P1（productType === 1）：一类用户，蓝色
      // P2（productType === 2, 3, 4）：二类用户，绿色
      // P3（productType === 5）：三类用户，橙色
      if (productType === 1) {
        // P1：一类用户，蓝色
        return {
          color: '#0081ff',
          backgroundColor: 'rgba(0, 129, 255, 0.1)'
        }
      } else if ([2, 3, 4].includes(productType)) {
        // P2：二类用户，绿色
        return {
          color: '#39B54A',
          backgroundColor: 'rgba(57, 181, 74, 0.1)'
        }
      } else if (productType === 5) {
        // P3：三类用户，橙色
        return {
          color: '#FBBD08',
          backgroundColor: 'rgba(251, 189, 8, 0.1)'
        }
      } else {
        // 默认使用二类用户的颜色
        return {
          color: '#39B54A',
          backgroundColor: 'rgba(57, 181, 74, 0.1)'
        }
      }
    }
  },
  methods: {
    extractSaleAreaCity(area) {
      if (!area || typeof area !== 'string') {
        return ''
      }

      let normalized = area.replace(/[\/|,，]/g, ' ').trim()
      if (!normalized) {
        return ''
      }

      const segments = normalized.split(/\s+/).filter(Boolean)
      if (segments.length >= 2) {
        return segments.slice(-2).join(' ')
      }

      const provinceMatch = normalized.match(/(.+?(省|自治区|特别行政区))/)
      if (provinceMatch) {
        const rest = normalized.substring(provinceMatch[0].length).trim()
        if (rest) {
          return rest
        }
      }

      return normalized
    },

    // 提取市级地址（用于 productType =1,3 目的地,泛营地）
    // 例如 "福建省漳州市龙文区" -> "漳州"
    extractCityLevel(area) {
      if (!area || typeof area !== 'string') {
        return ''
      }
      // 查找"市"的位置
      const cityIndex = area.indexOf('市')
      if (cityIndex > 0) {
        // 提取"市"字前面的部分
        let cityName = area.substring(0, cityIndex)
        // 去掉省、自治区等前缀
        const provinceIndex = cityName.lastIndexOf('省')
        const regionIndex = cityName.lastIndexOf('自治区')
        if (provinceIndex >= 0) {
          cityName = cityName.substring(provinceIndex + 1)
        } else if (regionIndex >= 0) {
          cityName = cityName.substring(regionIndex + 2)
        }
        return cityName
      }
      return ''
    },

    // 提取区级地址（用于 productType = 2, 4, 5 组团与综合研学与研学活动）
    // 例如 "福建省漳州市龙文区" -> "龙文"
    extractDistrictLevel(area) {
      if (!area || typeof area !== 'string') {
        return ''
      }
      // 查找"区"或"县"的位置
      const districtIndex = area.indexOf('区')
      const countyIndex = area.indexOf('县')
      let targetIndex = -1
      
      if (districtIndex !== -1 && countyIndex !== -1) {
        // 如果同时有"区"和"县"，取较近的一个
        targetIndex = Math.min(districtIndex, countyIndex)
      } else if (districtIndex !== -1) {
        targetIndex = districtIndex
      } else if (countyIndex !== -1) {
        targetIndex = countyIndex
      }
      
      if (targetIndex > 0) {
        // 提取"区"或"县"字前面的部分
        let districtName = area.substring(0, targetIndex)
        // 查找"市"的位置，取"市"后面的部分
        const cityIndex = districtName.indexOf('市')
        if (cityIndex >= 0) {
          districtName = districtName.substring(cityIndex + 1)
        } else {
          // 如果没有"市"，去掉省、自治区等前缀
          const provinceIndex = districtName.lastIndexOf('省')
          const regionIndex = districtName.lastIndexOf('自治区')
          if (provinceIndex >= 0) {
            districtName = districtName.substring(provinceIndex + 1)
          } else if (regionIndex >= 0) {
            districtName = districtName.substring(regionIndex + 2)
          }
        }
        return districtName
      }
      return ''
    },

    // 从完整地址中提取市级（用于 mergedItineraries 地址）
    // 例如 "福建省漳州市龙文区" -> "漳州"
    extractCityFromAddress(address) {
      if (!address || typeof address !== 'string') {
        return ''
      }
      const cityIndex = address.indexOf('市')
      if (cityIndex > 0) {
        let cityName = address.substring(0, cityIndex)
        const provinceIndex = cityName.lastIndexOf('省')
        const regionIndex = cityName.lastIndexOf('自治区')
        if (provinceIndex >= 0) {
          cityName = cityName.substring(provinceIndex + 1)
        } else if (regionIndex >= 0) {
          cityName = cityName.substring(regionIndex + 2)
        }
        return cityName
      }
      return ''
    },

    // 从完整地址中提取区级（用于 mergedItineraries 地址）
    // 例如 "福建省漳州市龙文区" -> "龙文"
    extractDistrictFromAddress(address) {
      if (!address || typeof address !== 'string') {
        return ''
      }
      // 查找"区"或"县"的位置
      const districtIndex = address.indexOf('区')
      const countyIndex = address.indexOf('县')
      let targetIndex = -1
      
      if (districtIndex !== -1 && countyIndex !== -1) {
        targetIndex = Math.min(districtIndex, countyIndex)
      } else if (districtIndex !== -1) {
        targetIndex = districtIndex
      } else if (countyIndex !== -1) {
        targetIndex = countyIndex
      }
      
      if (targetIndex > 0) {
        let districtName = address.substring(0, targetIndex)
        // 查找"市"的位置，取"市"后面的部分
        const cityIndex = districtName.indexOf('市')
        if (cityIndex >= 0) {
          districtName = districtName.substring(cityIndex + 1)
        } else {
          const provinceIndex = districtName.lastIndexOf('省')
          const regionIndex = districtName.lastIndexOf('自治区')
          if (provinceIndex >= 0) {
            districtName = districtName.substring(provinceIndex + 1)
          } else if (regionIndex >= 0) {
            districtName = districtName.substring(regionIndex + 2)
          }
        }
        return districtName
      }
      return ''
    },

    getProductTypeSuffix(productType) {
      const type = Number(productType)
      if ([1, 3].includes(type)) {
        return '接待'
      }
      if ([2, 4].includes(type)) {
        return '接送'
      }
      return ''
    },

    getTagStyle(tag) {
      if (tag && tag.isPlaceholder) {
        return {
          color: '#999999',
          backgroundColor: '#f0f0f0'
        }
      }
      return this.baseTagStyle
    },

    // 图片加载失败处理
    onImageError(e) {
      console.warn('Product image load failed:', e)
      // 可以在这里设置默认图片
    },

    // 点击产品卡片事件
    onCardClick() {
      this.$emit('click', this.info)
    },

    // 跳转到产品详情页
    goToProductDetail() {
      const productId = this.info.mainInfo?.productSpu?.id || this.info.id
      if (productId) {
        uni.navigateTo({
          url: `/public/productInfo/productInfo?id=${productId}`
        })
      } else {
        uni.showToast({ title: '产品ID不存在', icon: 'none' })
      }
    }
  }
}
</script>

<style lang="scss">
.product-card {
  // padding: 20rpx;
  // background-color: #FFFFFF;
  // border-radius: 12rpx;
  // box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 1rpx 5rpx rgba(0, 0, 0, 0.05);
  }
}

/* 顶部信息区 */
.top-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;

  .left-text {
    font-size: 28rpx;
    font-weight: bold;
    color: #666;
  }

  .right-status {
    font-size: 24rpx;
    color: #999;
    background: rgba(153, 153, 153, 0.1);
    border-radius: 4rpx;
    padding: 5rpx 15rpx;
  }
}

/* 主要内容区 */
.content-area {
  display: flex;

  .image-container {
    width: 180rpx;
    height: 180rpx;
    border-radius: 8rpx;
    overflow: hidden;
    background-color: #f5f5f5;

    .product-image {
      width: 100%;
      height: 100%;
    }
  }

  .info-container {
    margin-left: 20rpx;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
}

/* 产品标题 */
.product-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #303030;
  line-height: 1.4;
}

/* 基本信息区 */
.basic-info {
  display: flex;
  // margin: 12rpx 0;
  flex-wrap: nowrap;

  .info-item {
    display: flex;
    align-items: center;
    margin-right: 20rpx;
    margin-bottom: 8rpx;

    .info-text {
      // margin-left: 8rpx;
      font-size: 24rpx;
      color: #999999;
      flex-shrink: 0;
    }
  }
}

/* 标签和价格区 */
.tag-price-container {
  font-size: 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4rpx;

  .tags-container {
    display: flex;
    flex-wrap: wrap;

    .tag-item {
      padding: 5rpx 15rpx;
      margin-right: 10rpx;
      border-radius: 12rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 12em;
      // 默认样式会被动态样式覆盖
    }
  }

  .price-container {
    display: flex;
    align-items: baseline;

    .price-symbol {
      font-size: 26rpx;
      color: #787878;
    }

    .price-value {
      display: inline-flex;
      align-items: baseline;
      color: #787878;

      .currency {
        font-size: 24rpx;
        margin-right: 2rpx;
      }

      .price-int {
        font-size: 30rpx; // 左侧比右侧大2rpx
        font-weight: 600;
        line-height: 1;
      }

      .price-dec {
        font-size: 28rpx;
        font-weight: 500;
        line-height: 1;
      }
    }
  }
}

/* 日期选择区 */
.date-selector {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  padding-top: 16rpx;
  border-top: 1rpx solid #f0f0f0;

  .date-box {
    background: #78A329;
    border-radius: 4rpx;
    padding: 6rpx 15rpx;
    color: #fff;
    margin-left: 20rpx;
    font-size: 24rpx;
  }
}

/* 订单模式样式 */
.product-card.order-mode {
  background: transparent;
  box-shadow: none;
  padding: 0;
}

.product-card.order-mode .content-area {
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 图片容器点击效果 */
.image-container {
  position: relative;
  cursor: pointer;
  transition: opacity 0.2s;
}

.image-container:active {
  opacity: 0.8;
}

.product-card.order-mode .tag-item.pickup-tag {
  background: #78A329;
  color: #fff;
}

/* 订单模式下的价格样式 */
.product-card.order-mode .price-container {
  .price-value {
    color: #fc4735;

    .currency {
      font-size: 26rpx;
    }

    .price-int {
      font-size: 32rpx;
    }

    .price-dec {
      font-size: 30rpx;
    }
  }
}

/* 文本截断样式 */
.ellipsis-multi {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  text-overflow: ellipsis;
}

.ellipsis-single {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.info-icon {
  color: #999;
  margin-right: 20rpx;
  margin-left: 20rpx;
}
</style>